package cn.yotta.user.core.web.iface.impl;

import cn.yotta.user.api.vo.TokenVo;
import cn.yotta.user.core.web.iface.TokenStorageStrategy;
import cn.yotta.user.core.web.properties.LoginTokenProperties;
import cn.yotta.user.web.autoconfiguration.token.CookieLoginTokenObtainStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author wyaoyao
 * @date 2023/3/10 13:26
 * cookie存储
 */
@Slf4j
public class CookieTokenStorageStrategy extends CookieLoginTokenObtainStrategy implements TokenStorageStrategy {

    private final LoginTokenProperties tokenProperties;

    public CookieTokenStorageStrategy(LoginTokenProperties tokenProperties) {
        super(tokenProperties.getCookieName());
        this.tokenProperties = tokenProperties;
    }

    @Override
    public void save(TokenVo token) {
        final String cookieName = tokenProperties.getCookieName();
        final Cookie cookie = new Cookie(cookieName, token.getToken());
        cookie.setDomain(tokenProperties.getCookieDomain());
        cookie.setPath(tokenProperties.getCookiePath());
        cookie.setHttpOnly(false);
        cookie.setSecure(false);
        // 设置 cookie 过期时间与token过期时间一致
        cookie.setMaxAge(token.getExpireSecond());
        HttpServletResponse servletResponse = getHttpServletResponse();
        servletResponse.addCookie(cookie);
    }

    @Override
    public void remove() {
        final String tokenCookie = getTokenFromCookie();
        if (Objects.isNull(tokenCookie)) {
            return;
        }
        final String cookieName = tokenProperties.getCookieName();
        final String cookiePath = tokenProperties.getCookiePath();
        final String cookieDomain = tokenProperties.getCookieDomain();
        // 清除 token 在 cookie 中的有效期
        Cookie cookie = new Cookie(cookieName, null);
        cookie.setMaxAge(0);
        cookie.setPath(cookiePath);
        cookie.setDomain(cookieDomain);
        HttpServletResponse servletResponse = getHttpServletResponse();
        servletResponse.addCookie(cookie);
    }



    private HttpServletResponse getHttpServletResponse() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        return requestAttributes.getResponse();
    }
}
